<template>
  <div>
    <Modal
      :closable="false"
      :width="650"
      :mask-closable="false"
      v-model="editorBool"
      :title="modalTitle[modalType]"
      @on-ok="modalAppend"
      @on-cancel="modalCancel">
      <div id="editorElem" style="position: relative;">
        <span @click="appendEditor('__')" v-if="subjectType == 4 && modalType === 'question'" style="position: absolute; right: 10px;top: 7px; cursor: pointer;">插入填空</span>
      </div>
    </Modal>
    <div class="layout-content" v-for="(items, idx) in papers" :key="idx">
      <div v-for="(item, index) in items.subject" :class="!item.status && index === 0? 'error': ''" class="subject active" :key="index">
        <div class="active-checkmark"></div>
        <Icon type="android-done"></Icon>
        <div class="subject-close">
          <Poptip
            confirm
            title="删除无法恢复哦！"
            placement="bottom-end"
            @on-ok="handleDel(idx, index)">
            <Icon type="close"></Icon>
          </Poptip>
        </div>

        <div class="title">
          <span class="pull-left num">{{ index + 1 }}</span>
          <div class="pull-left mar-r-20">
            <span>题型：</span>
            <Dropdown trigger="click">
              <Button type="ghost"  style="width: 100px;">
                {{subjectTypeList[item.type - 1].label}}
                <Icon type="arrow-down-b"></Icon>
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem :disabled="item1.value === item.type" v-for="item1 in subjectTypeList" :key="item1.value" @click.native="changeType(item1.value, idx, index)">{{ item1.label }}</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
          <div class="pull-left mar-r-20">
            <span>资源编号：</span>
            <span>Q1072830</span>
          </div>

          <div class="pull-left mar-r-20">
            <span>知识点：</span>
            <Select v-model="knowledge" style="width:100px" placeholder="其他">
              <Option v-for="item2 in knowledgeList" :value="item2.value" :key="item2.value">{{ item2.label }}</Option>
            </Select>
          </div>

          <div class="pull-left mar-r-20">
            <InputNumber :max="100" :step="0.1" :min="1" :value="item.score" @on-change="changeScore($event, idx, index)"></InputNumber>
            <span>分</span>
          </div>

          <div class="pull-right mar-r-20">
            <Button type="text" icon="arrow-up-a" v-if="index !== 0" @click="move(idx, index, 'up')">上移</Button>
            <Button type="text" icon="arrow-down-a" v-if="index !== (items.subject.length - 1)" @click="move(idx, index, 'down')">下移</Button>
            <Button type="success" icon="ios-redo" v-if="!item.status" @click="setStatus(idx, index, true)">保存</Button>
            <Button type="warning" icon="ios-compose-outline" v-if="item.status" @click="setStatus(idx, index, false)">编辑</Button>
          </div>
        </div>
        <div class="question" @click="showModal('question', idx, index)">
          <div v-if="item.type == 4" class="text-red">直接输入2个连续下划线、或点击工具条上最右方的“插入填空”按钮，系统会自动识别为填空</div>
          <div v-if="item.question" v-html="item.question"></div>
          <span v-else class="null">还没有题干，点击此处 <span class="text-blue">添加题干</span></span>
        </div>
        <div v-if="!item.status">
          <div class="answer" v-if="item.type == 1 || item.type == 2">
            <RadioGroup :value="item.trueAnswer" vertical v-if="item.type == 1">
              <Radio @click.native="handleSetTrueAnswer(idx, index, i)" :label="letter[i]" v-for="(item3, i) in item.answer" :key="i">
                <span
                  class="null"
                  v-if="item3 === ''"
                  @click.stop.prevent="showModal('answer', idx, index, i)">
                  <span>{{letter[i]}}、 还未有选项内容，点击此处</span>
                  <span class="text-blue">添加内容</span>
                </span>
                <span
                  class="answer-item"
                  v-else
                  @click.stop.prevent="showModal('answer', idx, index, i)">
                <span>{{letter[i]}}、</span>
                <span v-html="item3"></span>
              </span>
                <span @click.stop.prevent="handleDelAnswer(idx, index, i)"><Icon type="close" class="answer-close"></Icon></span>
              </Radio>
            </RadioGroup>

            <CheckboxGroup :value="item.trueAnswer" class="inline" v-if="item.type == 2">
              <Checkbox @click.native="handleSetTrueAnswer(idx, index, i)" :label="letter[i]" v-for="(item3, i) in item.answer" :key="i">
              <span
                class="null"
                v-if="item3 === ''"
                @click.stop.prevent="showModal('answer', idx, index, i)">
                <span>{{letter[i]}}、 还未有选项内容，点击此处</span>
                <span class="text-blue">添加内容</span>
              </span>
                <span
                  class="answer-item"
                  v-else
                  @click.stop.prevent="showModal('answer', idx, index, i)">
                <span>{{letter[i]}}、</span>
                <span v-html="item3"></span>
              </span>
                <span @click.stop.prevent="handleDelAnswer(idx, index, i)"><Icon type="close" class="answer-close"></Icon></span>
              </Checkbox>
            </CheckboxGroup>
            <div class="append-answer" v-if="item.answer.length < 10 && (item.type == 2 || item.type == 1)">
              <Button @click="handleAppendAnswer(idx, index)" type="text" class="text-blue" icon="plus" size="small">添加一个选项</Button>
            </div>
          </div>

          <div class="answer" v-if="item.type == 3">
            <RadioGroup :value="item.trueAnswer" vertical>
              <Radio @click.native="handleSetTrueAnswer(idx, index, i)" :label="i" v-for="(item3, i) in item.answer" :key="i">
                <span>{{item3}}</span>
              </Radio>
            </RadioGroup>
          </div>

          <div class="answer" v-if="item.type == 4 && item.trueAnswer.length">
            <div style="line-height: 30px;"><b class="text-red">设置正确答案</b></div>
            <div v-for="(item3, i) in item.trueAnswer" :key="i" style="margin-bottom: 8px;">
              <div class="pull-left mar-r-20">
                <Input @on-change="inputAnswer($event, idx, index, i)" :value="item3" placeholder="请填写正确答案" style="width: 200px" />
              </div>

              <div class="pull-left mar-r-20">
                <InputNumber @on-change="inputDetailedScore($event, idx, index, i)" :step="0.1" :max="100" :min="1" :value="item.detailedScore[i]"></InputNumber>
                <span>分</span>
              </div>
              <div class="clearfix"></div>
            </div>
          </div>

          <div class="line" v-if="item.type == 1 || item.type == 2 || item.type == 3 || item.type == 4"></div>

          <div class="subject-content">
            <p class="title">解析内容</p>
            <div class="content" @click="showModal('content', idx, index)">
              <div v-if="item.content" v-html="item.content"></div>
              <div v-else><span class="null">还没有解析，点击此处 <span class="text-blue">添加解析</span></span></div>
            </div>
          </div>
        </div>

      </div>
      <div v-if="!items.subject.length" class="nothing" @click="unshiftSubject(idx)">
        <p>还没有题目 <span class="text-blue">添加题目</span></p>
      </div>
    </div>
  </div>
</template>
<script>
  import E from 'wangeditor'
  import { subjectTypeList } from '@/lib/config'
  import { mapState } from 'vuex'
  export default{
    mounted() {
      this.editor = new E('#editorElem')
      // 自定义菜单配置
      this.editor.customConfig.menus = [
        'image',  // 插入图片
        'video',  // 插入视频
        'link',  // 插入链接
      ]
      this.editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器
      this.editor.customConfig.onchange = (html) => {
        this.editorContent = html
      }
      this.editor.create()
    },
    computed: {
      ...mapState({
        papers: state => state.testPapers.papers
      }),
      letter() {
        let letter = []
        for(let i=0; i<10; i++) {
          letter.push(String.fromCharCode(65 + i))
        }
        return letter
      }
    },
    data() {
      return {
        err: false, // 用于显示题目边框
        index: null, // 试卷索引
        idx: null,  //题目索引
        modalTitle: {
          question: '设置题干',
          answer: '设置答案',
          content: '设置解析内容'
        },
        modalType: '',
        subjectType: null,
        editor: null,
        editorContent: '',
        editorBool: false,
        knowledge: 0,
        subjectTypeList: subjectTypeList,
        knowledgeList: [{
          label: '组成细胞的分子的构成',
          value: 1
        }],
      }
    },
    methods: {
      //切换题型
      changeType(e, idx, index) {
        if (this.papers[idx].subject[index].type === e) {
          return
        }
        this.$Modal.confirm({
          title: '提示',
          content: '修改题型将导致当前设置的答案丢失，是否确认题型修改？',
          onOk: () => {
            //idx 试卷索引  index 题目索引
            this.subjectType = e
            this.$store.commit('changePaperType', { idx, index, type: e })
          }
        })
      },
      //修改分数
      changeScore(e, idx, index) {
        this.$store.commit('changePaperScore', { idx, index, score: e })
      },
      //删除大题
      handleDel(idx, index) {
        this.$store.commit('delPaper', {idx, index})
      },
      // 清空富文本
      modalCancel() {
        this.editor.txt.clear()
        this.editorContent = ''
      },
      //对富文本编辑器追加html
      appendEditor(str) {
        this.editor.txt.append('<span>' + str + '</span>')
        this.editor.change && this.editor.change()
      },
      //显示富文本编辑器
      showModal(type, idx, index, i = null) {
        this.editorBool = true
        this.modalType = type
        this.index = index
        this.idx = idx
        switch (type) {
          case 'question':
            this.editorContent = this.papers[idx].subject[index].question
            break;
          case 'answer':
            this.editorContent = this.resAnswer(idx, index, i)
            this.answerIndex = i // 将当前点击的索引记录，编辑后需要匹配
            break;
          case 'content':
            this.editorContent = this.papers[idx].subject[index].content
            break;
          default:
            this.editorContent = ''
            break;
        }
        this.editor.txt.append(this.editorContent)
      },
      // 富文本提交数据
      modalAppend() {
        switch (this.modalType) {
          case 'question':
            this.$store.commit('setPaperQuestion', {
              idx: this.idx,
              index: this.index,
              question: this.editorContent.replace(/p>/g,"span>").replace(/<br>/g,"").replace(/<span><\/span>/g,"")
            })
            break;
          case 'answer':
            this.$store.commit('setPaperAnswer', {
              idx: this.idx,
              index: this.index,
              i: this.answerIndex,
              answer: this.editorContent.replace(/<p>(.*?)<\/p>/g,"$1").replace(/<br>/g,"")
            })
            this.answerIndex = null // 还原 answerIndex ，防止出现意外
            break;
          case 'content':
            this.$store.commit('setPaperContent', {
              idx: this.idx,
              index: this.index,
              content: this.editorContent
            })
            break;
          default:
            this.editorContent = ''
            break;
        }
        this.editorContent = ''
        this.editor.txt.clear()
      },
      // 编辑问题答案选项时，需要根据type判断选项是数组还是文字
      resAnswer(idx, index, i) {
        // 单选 多选
        const { type, answer } = this.papers[idx].subject[index]
        if([1, 2].indexOf(type) !== -1) {
          return '<p>' + answer[i] + '</p>'
        }
      },
      // 删除 单选 多选 答案选项
      handleDelAnswer(idx, index, i = null) {
        this.$store.commit('delPaperAnswer', {idx, index, i})
      },
      // 添加一个 单选 多选的 答案选项
      handleAppendAnswer(idx, index) {
        this.$store.commit('addPaperAnswer', {idx, index})
      },
      // 选择某一个 答案作为标准答案
      handleSetTrueAnswer(idx, index, i = null) {
        this.$store.commit('setPaperTrueAnswer', {idx, index, i, answer: ''})
      },

      //对数据进行上移下移
      move(idx, index, direction) {
        this.$store.commit('setPaperDirection', {idx, index, direction})
      },

      //添加题目
      unshiftSubject(i) {
        if (!this.$store.getters.getPaperStatus) {
          this.$Message.error('请完成当前新增题型');
          return
        }
        this.$store.commit('addPaper', i)
      },

      //正确答案输入事件
      inputAnswer(e, idx, index, i) {
        this.$store.commit('setPaperTrueAnswer', {idx, index, i, answer: e.target.value})
      },

      //输入分值时
      inputDetailedScore(e, idx, index, i) {
        this.$store.commit('setPaperDetailedScore', {idx, index, i, score: e})
      },

      setStatus(idx, index, status) {
        if (status) {
          let { question, type, answer, trueAnswer } = this.papers[idx].subject[index]
          if(!question.trim()) {
            this.$Message.error('请设置题干')
            return
          }
          if((type == 3 || type == 1) && (trueAnswer === '' || trueAnswer === null)) {
            this.$Message.error('请设置正确答案')
            return
          }
          if(type == 2 && !trueAnswer.length) {
            this.$Message.error('请设置正确答案')
            return
          }
        }
        this.$store.commit('setStatus', {idx, index, status})
      }
    }
  }
</script>
<style scoped>
  .ivu-radio-group-vertical .ivu-radio-wrapper{
    height: inherit !important;
  }
  .subject{
    margin-top: 15px;
    background: #fff;
    padding: 5px 20px;
    position: relative;
    border: 3px solid #fff;
  }
  .subject.error{
    border: 2px solid #ed3f14;
  }
  .subject .active-checkmark{
    position: absolute;
    width: 0px;
    height: 0px;
    z-index:1;
    border-width: 0px 0px 30px 30px;
    border-style: solid;
    top: -3px;
    left: -3px;
  }
  .subject-close{
    position: absolute;
    z-index: 2;
    right: 0px;
    top: 0px;
  }
  .subject-close .ivu-icon{
    height: 30px;
    width: 30px;
    font-size: 16px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
    transition: all 0.45s;
    -moz-transition: all 0.45s; /* Firefox 4 */
    -webkit-transition: all 0.45s; /* Safari and Chrome */
    -o-transition: all 0.45s; /* Opera */
  }
  .subject-close .ivu-icon:hover{
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    transform: rotate(90deg);
  }
  .subject .active-checkmark{
    border-color: transparent #e0e0e0;
  }
  .subject.active .active-checkmark{
    border-color: transparent #55bba4;
  }
  .subject .ivu-icon-android-done{
    position: absolute;
    top: -3px;
    left: -3px;
    width: 30px;
    height: 30px;
    z-index: 2;
    line-height: 18px;
    font-size: 16px;
    padding-left: 5px;
    color: #fff;
  }
  .subject .title{
    height: 50px;
    line-height: 50px;
  }
  .subject .title .num{
    width: 30px;
    font-weight: 500;
    text-align: left;
  }
  .mar-r-20{
    margin-right: 20px;
  }
  .question{
    border: 1px dashed #dddddd;
    padding: 10px 15px;
    background: #fbfeff;
    margin-top: 10px;
    border-radius: 5px;
    line-height: 30px;
  }
  .null{
    cursor: pointer;
  }
  .answer{
    padding: 10px;
  }
  .answer-radio li{
    line-height: 30px;
    height: 30px;
  }
  .answer .answer-close{
    margin-left: 15px;
    display: none;
    height: 100%;
    text-align: center;
    cursor: pointer;
  }
  .answer .ivu-radio-wrapper:hover .answer-close, .answer .ivu-checkbox-group-item:hover .answer-close{
    display: inline-block;
  }
  .append-answer{
    margin-top: 5px;
    margin-left: -5px;
  }
  .subject-content{
    padding: 10px;
  }
  .subject-content .title{
    height: 30px;
    line-height: 30px;

  }
  .subject-content .content{
    margin-top: 10px;
  }
  .answer-item *{
    display: inline-block !important;
  }
  .inline .ivu-checkbox-group-item{
    display: block;
    line-height: 30px;
  }
</style>
